<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Payment
 * @subpackage Gateway
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id:  $
 */


/**
 * @see Zend_Payment
 */
require_once 'Zend/Payment.php';


/**
 * Class for online Ecommerce charging/payments
 *
 * @category   Zend
 * @package    Zend_Payment
 * @subpackage Gateway
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id:  $
 */
class Zend_Payment_Gateway_Tranzila extends Zend_Payment_Gateway_Abstract
{

	/**
     * Required options per gateways, things such as suplier, merchant account id
     * email addresess
     * 
     * Other:
     * 		 'gatewayNamespace' => custom namespace for a gateway
     *
     * @var array
     */
	public $_options = array(

	'supplier' => null, // supplier name

	);

	/**
	 * Uri for the gateway
	 *
	 * @var string
	 */
	private $_uri = 'https://secure5.tranzila.com/cgi-bin/tranzila31.cgi'; // gateway uri

	/**
	 * Language strings
	 *
	 * @var array
	 */
	public $_error_strings = array(
	'error999' => 'The request could not reach it\'s destination',
	'error004' => 'Credit Card was declined',
	'error006' => 'CVV Number is invalid',
	'error033' => 'Credit Card Number is invalid',
	'error036' => 'Credit Card expired',
	'error057' => 'Please specify credit card number',
	'error062' => 'Transaction type is invalid',
	'error063' => 'Transaction Code is invalid',
	'error064' => 'Credit card type is not supported',
	'error065' => 'Currency type is invalid');

	/**
     * Constructor.
     *
     * $options is an array of key/value pairs or an instance of Zend_Config
     * containing configuration options.
     *
     * @param  array|Zend_Config $options An array or instance of Zend_Config having configuration data
     * @throws Zend_Payment_Exception
     */
	public function __construct($options)
	{
		parent::__construct($options);
	}


	/**
     * Abstract Methods
     */


	/**
     * Check for config options that are mandatory.
     *
     * @throws Zend_Payment_Gateway_Exception
     */
	public function _checkRequiredOptions()
	{
		if(!$this->_options['supplier'])
		{
			$this->_error_string = "Supplier must be specifed";
			$this->_errorcode = Zend_Payment_Gateway_Abstract::GATEWAY_INACCESSIBLE;

			if($this->_options['exceptions'])
			{
				throw new Zend_Payment_Gateway_Exception("Supplier must be specifed");
			}
		}
	}
	
	/**
	 * Transaction failed
	 *
	 * @param array $params
	 * @return boolean
	 */
	public function isFailed( $params=array() )
	{
		return $this->_error_string ? true : false;
	}

	/**
	 * Was the transaction successful
	 *
	 * @param array $params
	 * @return boolean
	 */
	public function isSuccess( $params=array() )
	{
		return $this->_error_string == '' ? true : false;
	}

	/**
     * Do Charge method
     *
     */
	public function doCharge()
	{
		# Load the client
		$client = new Zend_Http_Client();
		$client->setUri( $this->_uri );

		# Config options
		$client->setConfig(array(
		'maxredirects' => 0,
		'timeout'      => 30));

		# Set suplier value
		$client->setParameterGet( 'supplier' , $this->_options['supplier'] );

		# Add all other values
		foreach ($this->_fields as $key => $value)
		{
			$client->setParameterGet($key, urlencode($value));
		}

		# Send
		$response = $client->request();

		if(!$response)
		{
			$this->_error_string = $response->getMessage();
			$this->_errorcode = $response->getStatus();
		}

		# Get response
		$this->_response = $response->getBody();

		//-------------------------------------
		// Response example:
		// Response=033&fname=%e0%f4%e9&expmonth=02&contact=%e0%f4%e9%20%e1%e5%f8%e5%eb%e5%e1&
		// description=RentCenter%20-%20%e7%e9%e5%e1%20%f2%e1%e5%f8%20%ee%e5%f6%f8%e9%ed%20%f9%e4%e5%e6%ee%f0%e5&
		// orderid=3438&email=&ccno=234234234234&expyear=09&npay=1&supplier=123&lname=%e1%e5%f8%e5%eb%e5%e1&
		// IMaam=0.155&CVVstatus=0&company=%e0%f4%e9%20%e1%e5%f8%e5%eb%e5%e1&sum=1&ConfirmationCode=0000000&index=3178&
		// Tempref=74550001&CVVstatus=0&Responsesource=0
		//
		// If the request did not even reach the gateway then an HTML page will be displayed
		// with an error string, In that case we will just print the error returned from the HTML
		// or a default error string
		//
		//-------------------------------------

		# Search for an HTML tag in the response
		if(strpos($this->_response, '<html>') !== false)
		{
			# Attempt to grab the error string returned by the gateway
			preg_match( '#<font color=red>(.*?)</font>#', $this->_response, $matches);

			$this->_error_string = $matches[1] ? trim($matches[1]) : $this->_error_strings['error'];
			$this->_errorcode = Zend_Payment_Gateway_Abstract::GATEWAY_INACCESSIBLE;
			return;
		}

		# Explode the response & assigne the values to the response array
		$exploded_response = explode('&', $this->_response);
		foreach($exploded_response as $key => $value)
		{
			unset($tmparr);
			$tmparr = explode("=",$value);
			$this->_response[$tmparr[0]] = urldecode($tmparr[1]);
		}

		# Build the error string and error codes basd on the response
		switch($this->_response["Response"])
		{
			case '004':
				$this->_error_string = $this->_error_strings['error004'];
				$this->_errorcode = Zend_Payment_Gateway_Abstract::DECLINED;
				break;
			case '006':
			case '017':
			case '058':
			case '059':
				$this->_error_string = $this->_error_strings['error006'];
				$this->_errorcode = Zend_Payment_Gateway_Abstract::CVV_INVALID;
				break;

			case '033':
				$this->_error_string = $this->_error_strings['error033'];
				$this->_errorcode = Zend_Payment_Gateway_Abstract::CCNUMBER_INVALID;
				break;

			case '036':
				$this->_error_string = $this->_error_strings['error036'];
				$this->_errorcode = Zend_Payment_Gateway_Abstract::CCNUMBER_EXPIRED;
				break;

			case '057':
			case '059':
				$this->_error_string = $this->_error_strings['error057'];
				$this->_errorcode = Zend_Payment_Gateway_Abstract::CCNUMBER_MISSING;
				break;

			case '062':
				$this->_error_string = $this->_error_strings['error062'];
				$this->_errorcode = Zend_Payment_Gateway_Abstract::TRANSACTION_TYPE_INVALID;
				break;

			case '063':
				$this->_error_string = $this->_error_strings['error063'];
				$this->_errorcode = Zend_Payment_Gateway_Abstract::TRANSACTION_CODE_INVALID;
				break;

			case '064':
				$this->_error_string = $this->_error_strings['error064'];
				$this->_errorcode = Zend_Payment_Gateway_Abstract::CREDIT_TYPE_NOT_SUPPORTED;
				break;

			case '065':
				$this->_error_string = $this->_error_strings['error065'];
				$this->_errorcode = Zend_Payment_Gateway_Abstract::CURRENCY_NOT_SUPPORTED;
				break;

			case '000':
				$this->_error_string = null; // This says it went trough so we empty the error_string
				$this->_errorcode = Zend_Payment_Gateway_Abstract::APPROVED;
				break;

			default:
				$this->_error_string = $this->_error_strings['error004'];
				$this->_errorcode = Zend_Payment_Gateway_Abstract::DECLINED;
				break;
		}
	}

}
